package com.zhao.blog.controller.admin;

import com.zhao.blog.pojo.Tag;
import com.zhao.blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.yaml.snakeyaml.tokens.TagToken;

/**
 * @author xiaoZhao
 * @date 2022/1/6
 * @describe
 */
@Controller
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private TagService service;

    //跳转至标签列表
    @GetMapping("/tags")
    public String tags(@PageableDefault(size = 5, sort = {"id"}, direction = Sort.Direction.ASC)
                                   Pageable pageable, Model model){
        model.addAttribute("page",service.listTags(pageable));
        return "admin/tags";
    }

    //跳转至新增页
    @GetMapping("/tags/toAddTags")
    public String toAddTags(Model model){
        model.addAttribute("tag",new Tag());
        return "admin/addTags";
    }

    //添加标签
    @PostMapping("/addTags")
    public String addTags(Tag tag, RedirectAttributes attributes){
        Tag t = service.saveTag(tag);
        if (t == null) {
            attributes.addFlashAttribute("message", "添加失败");
        } else {
            attributes.addFlashAttribute("message", "添加成功");
        }
        return "redirect:/admin/tags";
    }

    //跳转到更新标签页
    @GetMapping("/tags/{id}/editTags")
    public String toeditTags(Model model,@PathVariable Long id){
        model.addAttribute("tag",service.getTag(id));
        return "admin/addTags";
    }

    //修改
    @PostMapping("/editTags/{id}")
    public String editTags(Tag tag,@PathVariable Long id,RedirectAttributes attributes){
        Tag t = service.updateTag(id, tag);
        if (t == null) {
            attributes.addFlashAttribute("message", "更新失败");
        } else {
            attributes.addFlashAttribute("message", "更新成功");
        }
        return "redirect:/admin/tags";
    }


    //删除
    @GetMapping("/tags/{id}/delete")
    public String deleteType(@PathVariable Long id ,RedirectAttributes attributes){
        service.deleteTag(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/tags";
    }
}
